package com.imy.luascript.retrofit;




import com.imy.luascript.retrofit.ssl.TrustAllHostnameVerifier;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * OkHttp管理类
 *
 * @author: Imy
 * @date: 2017-03-04
 */
public class OkHttpProvider {
  //private static final String TAG = "OkHttpProvider";
  private final static long DEFAULT_CONNECT_TIMEOUT = 5;
  private final static long DEFAULT_WRITE_TIMEOUT = 7;
  private final static long DEFAULT_READ_TIMEOUT = 7;

  private final static int BACKUP_DNS_USE_NUM = 30;
  private static int backupDNSUseCounter = 0;

  //设缓存有效期为七天
  protected static final long CACHE_STALE_SEC = 60 * 60 * 24 * 7;



  public static OkHttpClient getOkHttpClient() {
    return getOkHttpClient(new FromNetWorkControlInterceptor());
  }

  /**
   * 自定义超时时间
   */
  public static OkHttpClient getOkHttpClient(int timeOut) {
    //定制OkHttp
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

    //SSL
    try {
      httpClientBuilder.sslSocketFactory(new SSLSocketFactoryCompat());
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    httpClientBuilder.hostnameVerifier(new TrustAllHostnameVerifier());

    //设置超时时间
    httpClientBuilder.connectTimeout(timeOut, TimeUnit.SECONDS);
    httpClientBuilder.writeTimeout(timeOut, TimeUnit.SECONDS);
    httpClientBuilder.readTimeout(timeOut, TimeUnit.SECONDS);
    //设置缓存
    //File httpCacheDirectory = new File(FileUtils.getCacheDir(HYKBApplication.getContext()),
    //    "OkHttpCache");
    //httpClientBuilder.cache(new Cache(httpCacheDirectory, 100 * 1024 * 1024));
    //设置拦截器


    httpClientBuilder.addInterceptor(new HttpInterceptor());//查看接口数据   byImy  如误上传代码 请屏蔽此行

    //if(BuildConfig.LOG_DEBUG ) {
    //  httpClientBuilder.addInterceptor(new ChuckInterceptor(HYKBApplication.getContext()));
    //}
/*    httpClientBuilder.addInterceptor(cacheControl);
    httpClientBuilder.addNetworkInterceptor(cacheControl);*/
    httpClientBuilder.retryOnConnectionFailure(true);//允许失败重试
    return httpClientBuilder.build();
  }

  private static OkHttpClient getOkHttpClient(Interceptor cacheControl) {
    //定制OkHttp
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    //SSL
    try {
      httpClientBuilder.sslSocketFactory(new SSLSocketFactoryCompat());
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
//    httpClientBuilder.sslSocketFactory(CertificateFactory.createSSLSocketFactory());
    httpClientBuilder.hostnameVerifier(new TrustAllHostnameVerifier());

    //设置超时时间
    httpClientBuilder.addInterceptor(new HttpInterceptor());//查看接口数据   byImy  如误上传代码 请屏蔽此行

    httpClientBuilder.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
    httpClientBuilder.writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
    httpClientBuilder.readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
    //设置缓存
    //File httpCacheDirectory = new File(FileUtils.getCacheDir(HYKBApplication.getContext()),
    //    "OkHttpCache");
    //httpClientBuilder.cache(new Cache(httpCacheDirectory, 100 * 1024 * 1024));
    //设置拦截器
    //拦截器处理有先后顺序，要把获取UserAgen的拦截器放在后面，不然获取UA的时候数据会有问题（多线程数据错乱）


    //if(BuildConfig.LOG_DEBUG ) {
    //  httpClientBuilder.addInterceptor(new ChuckInterceptor(HYKBApplication.getContext()));
    //}
    //httpClientBuilder.addInterceptor(new HttpInterceptor());//查看接口数据   byImy  如误上传代码 请屏蔽此行

/*    httpClientBuilder.addInterceptor(cacheControl);
    httpClientBuilder.addNetworkInterceptor(cacheControl);*/
    httpClientBuilder.retryOnConnectionFailure(true);//允许失败重试
    return httpClientBuilder.build();
  }



  /**
   * 强制从网络获取数据
   */
  private static class FromNetWorkControlInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      request = request.newBuilder()
          .cacheControl(CacheControl.FORCE_NETWORK)
          .build();
      Response response = chain.proceed(request);
      return response;
    }
  }

  private static class UserAgentInterceptor implements Interceptor {
    private static final String USER_AGENT_HEADER_NAME = "User-Agent";
    private final String userAgentHeaderValue;

    UserAgentInterceptor(String userAgentHeaderValue) {
      this.userAgentHeaderValue = userAgentHeaderValue;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();

      Request requestWithUserAgent = null;
      String url = originalRequest.url().toString();
      if (url.contains("globallaunch-home")) {
        requestWithUserAgent = originalRequest.newBuilder()
            .removeHeader(USER_AGENT_HEADER_NAME)
            .addHeader(USER_AGENT_HEADER_NAME, "Androidkb")
            //.addHeader("current-environ", "ot")
            .build();
      } else {
        requestWithUserAgent = originalRequest.newBuilder()
            .removeHeader(USER_AGENT_HEADER_NAME)
            //.addHeader("current-environ", "ot")
            .build();
      }

      return chain.proceed(requestWithUserAgent);
    }
  }


}
